from langchain_community.agent_toolkits import PlayWrightBrowserToolkit  
# 禁用LangSmith跟踪，避免网络连接问题
import os
os.environ["LANGCHAIN_TRACING_V2"] = "false"
os.environ["LANGCHAIN_API_KEY"] = ""
os.environ["LANGCHAIN_HUB_API_KEY"] = ""

# 导入必要的模块
from langchain_community.agent_toolkits import PlayWrightBrowserToolkit
from langchain_community.tools.playwright.utils import (
    create_async_playwright_browser,  # 使用异步浏览器避免greenlet线程问题
)
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
import asyncio
import traceback

# 定义适合OpenAI工具代理的prompt模板，避免使用需要额外变量的REACT格式
from langchain_core.prompts import ChatPromptTemplate

# 使用ChatPromptTemplate替代PromptTemplate，符合OpenAI工具代理的要求
system_message = """你是一个有用的助手，配备了一些工具来帮助完成任务。\n\n完成任务时，请使用提供的工具来获取信息。"""

prompt = ChatPromptTemplate.from_messages([
    ("system", system_message),
    ("placeholder", "{chat_history}"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])

# 使用异步浏览器
async_browser = create_async_playwright_browser()
toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)
tools = toolkit.get_tools()

# 初始化LLM模型
llm = ChatOpenAI(
    model_name="gpt-4.1",
)

# 构建OpenAI工具代理
agent = create_openai_tools_agent(llm, tools, prompt)

# 创建代理执行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 使用异步方式调用代理
async def run_agent():
    try:
        command = {
            "input": "访问 https://www.baidu.com，并总结页面上提到的所有工具。每一步都打印出URL。"
        }
        return await agent_executor.ainvoke(command)
    except Exception as e:
        print(f"执行过程中出错: {type(e).__name__}: {e}")
        traceback.print_exc()
        return {"error": str(e)}

# 运行agent并处理结果
try:
    result = asyncio.run(run_agent())
    print("结果:", result)
except KeyboardInterrupt:
    print("程序被用户中断")
except Exception as e:
    print(f"程序运行出错: {type(e).__name__}: {e}")
    traceback.print_exc()

